package com.mall.auth.controller;

import com.mall.auth.entity.OAuth2Provider;
import com.mall.auth.service.OAuth2Service;
import com.mall.common.entity.User;
import com.mall.common.result.Result;
import com.mall.common.util.RedisUtil;
import com.mall.system.feign.UserServiceFeignClient;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 账号绑定控制器
 * 处理用户账号与第三方平台账号的绑定操作
 */
@Tag(name = "账号绑定接口")
@Slf4j
@RestController
@RequestMapping("/auth/binding")
public class AccountBindingController {

    @Autowired
    private OAuth2Service oAuth2Service;
    
    @Autowired
    private UserServiceFeignClient userServiceFeignClient;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${oauth2.wechat.redirect-uri}")
    private String wechatRedirectUri;

    @Value("${oauth2.alipay.redirect-uri}")
    private String alipayRedirectUri;

    @Value("${oauth2.douyin.redirect-uri}")
    private String douyinRedirectUri;

    @Value("${oauth2.qq.redirect-uri}")
    private String qqRedirectUri;

    @Operation(summary = "生成绑定链接")
    @PostMapping("/generate/{provider}")
    public Result<Map<String, Object>> generateBindingUrl(
            @PathVariable("provider") String provider,
            @RequestParam Long userId) {
        try {
            OAuth2Provider providerEnum = OAuth2Provider.fromCode(provider);
            
            // 生成状态码，用于标识绑定操作
            String state = UUID.randomUUID().toString();
            
            // 存储绑定信息到Redis
            Map<String, Object> bindingInfo = new HashMap<>();
            bindingInfo.put("userId", userId);
            bindingInfo.put("provider", provider);
            bindingInfo.put("createTime", System.currentTimeMillis());
            redisUtil.set("user:binding:" + state, bindingInfo, 300); // 5分钟过期
            
            // 生成授权URL
            String redirectUri = getRedirectUri(providerEnum);
            String authorizationUrl = oAuth2Service.getAuthorizationUrl(providerEnum, redirectUri + "?state=" + state);
            
            Map<String, Object> result = new HashMap<>();
            result.put("authorizationUrl", authorizationUrl);
            result.put("state", state);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("生成绑定链接异常: ", e);
            return Result.failed("生成绑定链接失败: " + e.getMessage());
        }
    }

    @Operation(summary = "解除第三方账号绑定")
    @DeleteMapping("/{provider}")
    public Result<String> unbindAccount(
            @PathVariable("provider") String provider,
            @RequestParam Long userId) {
        try {
            // 获取用户信息
            Result<User> userResult = userServiceFeignClient.getUserById(userId);
            if (!userResult.getCode().equals(200) || userResult.getData() == null) {
                return Result.failed("用户不存在");
            }
            
            User user = userResult.getData();
            
            // 检查用户是否绑定了指定的第三方平台账号
            String thirdPartyId = user.getThirdPartyId();
            if (thirdPartyId == null || !thirdPartyId.startsWith(provider + "_")) {
                return Result.failed("用户未绑定该平台的第三方账号");
            }
            
            // 移除thirdPartyId
            user.setThirdPartyId(null);
            Result<Boolean> updateResult = userServiceFeignClient.updateUser(user);
            
            if (!updateResult.getCode().equals(200) || !updateResult.getData()) {
                return Result.failed("解除绑定失败");
            }
            
            log.info("用户 {} 的 {} 账号绑定已解除", userId, provider);
            return Result.success("解除绑定成功");
        } catch (Exception e) {
            log.error("解除账号绑定异常: ", e);
            return Result.failed("解除账号绑定失败: " + e.getMessage());
        }
    }

    /**
     * 获取回调地址
     *
     * @param provider 第三方提供商
     * @return 回调地址
     */
    private String getRedirectUri(OAuth2Provider provider) {
        switch (provider) {
            case WECHAT:
                return wechatRedirectUri;
            case ALIPAY:
                return alipayRedirectUri;
            case DOUYIN:
                return douyinRedirectUri;
            case QQ:
                return qqRedirectUri;
            default:
                throw new IllegalArgumentException("不支持的OAuth2提供商: " + provider);
        }
    }
}